package peer.tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;

public class Md5Sum{
	public File file; 
	public Hashtable mht;
	public String[] mp;
	long fileLength;
	public Md5Sum(String fs){
		this.file=new File(fs);
	}
	public byte[][] handleFileInput(){
		byte[][] mdba=null;
		MessageDigest md=null ;
		fileLength=file.length();
		try {
			BufferedInputStream bis = null;
			FileInputStream fis;
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			
			int blockSum=(int) (file.length()/(512*1024));
			if((file.length())%(512*1024)!=0){
				blockSum+=1;
			}
			if(blockSum==0){
				blockSum=1;
			}
			mdba=new byte[blockSum][16];
			for(int blockNum=0;blockNum<blockSum;blockNum++){
				int blockLength=0;
				if(fileLength<=512*1024){
					blockLength=(int) fileLength;
					//System.out.println("DDDDDDDDDDDDD");
				}else{
					if(blockNum<blockSum-1){
						blockLength=512*1024;
						//System.out.println("AAAAAAAAAAAAAAA  "+blockLength);
					}else{
						blockLength=(int)(fileLength%(512*1024));
						//System.out.println("BBBBBBBBBBBBBBB  "+blockLength);
					}
				}
				byte[] buffer = new byte[blockLength];
				md= MessageDigest.getInstance("MD5");
				bis.read(buffer);
				md.update(buffer);
				mdba[blockNum]=md.digest();
			}
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return mdba;
	}
}
